import React from 'react';

/**

Let’s quickly recap what’s going on and the order in which the methods are called:
When <Clock /> is passed to ReactDOM.render(), React calls the constructor of the Clock component. Since Clock needs to display the current time, it initializes this.state with an object including the current time. We will later update this state.
React then calls the Clock component’s render() method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the Clock’s render output.
When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle method. Inside it, the Clock component asks the browser to set up a timer to call the component’s tick() method once a second.
Every second the browser calls the tick() method. Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.
If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.

*/
class StateExample extends React.Component{
	//入参props，代表了 组件之间传入参数
	//<StateExample user={}>, 实例化StateExample时，可从props.user 取入参 
	constructor(props){
		super(props);//必须第一步调用super(props),否而不存在this对象。
		//对 state 赋值。 state 固定对象，用于state中数据变化时，触发dom 的更新。
		this.state={
			date : new Date(),
			counter:0,
			title:"StateExample"
		};
	}

	//页面渲染完成之后被react自动调用
	componentDidMount(){
		this.timerId = setInterval(() => this.tick(),1000);
	}

	//页面被desory 时调用
 	componentWillUnmount(){
 			clearInterval(this.timerID);
 	}


 	tick() {
    	this.setState(function (state, props){
    		return ({
    					date: new Date(),
    					counter:state.counter+1
    			});
    	});
    	//setState 触发 dom render
    	// setState ({对象})，对象与原state对象合并。（以上未覆盖title属性）
    	//setState (),参数中尽量使用function(state,props){ return {}},做为入参，function中返回要
    	//           设置的state对象。
  	}
	render(){

		return (
				<div>
				<p>{this.state.title}</p>
				<p>{this.state.date.toLocaleTimeString()}</p>
				<p> counter:{this.state.counter}</p>
				</div>	
			);
	}
}
export default StateExample;